<?php

// +----------------------------------------------------------------------
// | Shop-Demo for ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2022~2023 Anyon <zoujingli@qq.com>
// +----------------------------------------------------------------------
// | 官方网站: https://thinkadmin.top
// +----------------------------------------------------------------------
// | 免责声明 ( https://thinkadmin.top/disclaimer )
// | 会员免费 ( https://thinkadmin.top/vip-introduce )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\data\controller\msjx;

use app\data\model\DataEnterpriseFreePolicy;
use app\data\model\DataMsjx as DataNewsItem;
use app\data\model\DataNoticePushLog;
use app\data\model\DataQiyeRzinfo;
use app\data\model\DataQiyeXinxiku;
use app\data\service\NewsService;
use app\data\service\NoticeService;
use think\admin\Controller;
use think\admin\extend\CodeExtend;
use think\admin\helper\QueryHelper;
use think\admin\service\AdminService;
use think\facade\Db;

/**
 * 免申即享
 * Class Item
 * @package app\data\controller\news
 */
class Msjx extends Controller
{
    /**
     * 内容管理
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $this->type = $this->get['type'] ?? 'index';
        DataNewsItem::mQuery($this->get)->layTable(function ()
        {
            $this->title = '免申即享';
        }, function (QueryHelper $query)
        {
            $query->like('code,title')->equal('tj_status')->dateBetween('create_at');
            $query->where(['status' => intval($this->type === 'index'), 'deleted' => 0]);
            $admin = AdminService::getUserId();
            if ($admin != 10000) {
                $query->whereRaw("admin_id = {$admin}");
            }
        });
    }

    /**
     * 列表数据处理
     * @param  array  $data
     */
    protected function _page_filter(array &$data)
    {

        foreach ($data as &$item) {

            if (!empty($item['qybq'])) {

                $qybq_array       = explode(',', $item['qybq']);
                $item['qybq_txt'] = '';
                $i                = 0;
                foreach ($qybq_array as $qybq_info) {
                    if ($i > 0) {
                        $item['qybq_txt'] .= ',';
                    }
                    $item['qybq_txt'] .= Db::name("data_qiye_biaoqian")->where('id', $qybq_info)->value('name');
                    $i++;
                }


            } else {
                $item['qybq_txt'] = '';
            }

            if (!empty($item['ctrq'])) {

                $item['ctrq'] = date('Y-m-d', $item['ctrq']);

            } else {
                $item['ctrq'] = '';
            }

            if (!empty($item['sbjzrq'])) {

                $item['sbjzrq'] = date('Y-m-d', $item['sbjzrq']);

            } else {
                $item['sbjzrq'] = '';
            }

            //            if($item['wztype'] == 1){
            //                $item['wztype_txt'] = '政策公告';
            //            }else{
            //                $item['wztype_txt'] = '政策申报';
            //            }
        }

    }

    /**
     * 添加文章内容
     */
    public function add()
    {
        $this->title = '添加内容';
        DataNewsItem::mForm('form');
    }

    /**
     * 编辑文章内容
     */
    public function edit()
    {
        $this->title = '编辑内容';
        DataNewsItem::mForm('form');
    }

    /**
     * 表单数据处理
     * @param  array  $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _edit_form_filter(array &$data)
    {

        if ($this->request->isGet()) {

        } else {

            Db::name("data_msjx_user")->where('msjx_id', $data['id'])->update(['title' => $data['title']]);

        }
    }

    /**
     * 表单数据处理
     * @param  array  $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _form_filter(array &$data)
    {
        if (empty($data['code'])) {//暂无code就生成一个
            $data['code'] = CodeExtend::uniqidNumber(20, 'A');
        }
        if ($this->request->isGet()) {
            if (!empty($data['ctrq'])) {
                $data['ctrq'] = date('Y-m-d', $data['ctrq']);
            }

            if (!empty($data['sbjzrq'])) {
                $data['sbjzrq'] = date('Y-m-d', $data['sbjzrq']);
            }

        } else {

            //日期转换时间戳
            if (!empty($data['ctrq'])) {
                $data['ctrq'] = strtotime($data['ctrq']);
            }

            if (!empty($data['sbjzrq'])) {
                $data['sbjzrq'] = strtotime($data['sbjzrq']);
            }


            //获取当前添加内容的管理员id
            $data['admin_id'] = AdminService::getUserId();

        }
    }

    /**
     * 表单结果处理
     * @param  boolean  $state
     */
    protected function _form_result(bool $state)
    {
        if ($state) {
            $req           = $this->request->all();
            $enterpriseIds = [];
            if ($req['enterprises'] === '') {
                $tags           = $req['qybq'] ?? '';
                $enterpriseList = DataQiyeXinxiku::query();
                if ($tags = $tags ? explode(',', $tags) : null) {
                    $row = '(';
                    foreach ($tags as $tag) {
                        // $enterpriseList = $enterpriseList->whereFindInSet('qybq', $tag);
                        $row .= "find_in_set('{$tag}',qybq) or ";
                    }
                    $row            = rtrim($row, 'or ');
                    $row            .= ')';
                    $enterpriseList = $enterpriseList->whereRaw($row);
                }
                $enterpriseList   = $enterpriseList->where('status', 1)->select()->toArray();
                $reqEnterpriseIds = array_column($enterpriseList, 'id');
            } else {
                $reqEnterpriseIds = explode(',', $req['enterprises']);
            }
            //根据企业id查询已经认证过的所有用户
            $authUser = DataQiyeRzinfo::query()->whereIn('qrxxk_id', $reqEnterpriseIds)->select()->toArray();
            // $userIds = array_column($authUser, 'user_id');
            $noticeInsertData = $freePolicyInsertData = [];
            //添加提示记录
            foreach ($authUser as $item) {
                $exists = DataNoticePushLog::query()->where('user_id', $item['user_id'])->where('policy_id', $req['id'])->find();
                //已存在的提示不再重复添加
                if ($exists) {
                    continue;
                }
                $noticeInsertData[] = [
                    'user_id'   => $item['user_id'],
                    'title'     => $req['title'],
                    'content'   => $req['content'],
                    'type'      => DataNoticePushLog::NOTICE_TYPE_FREE_POLICY,
                    'url'       => 'api/msjx/getMsjxInfo',
                    'policy_id' => $req['id'],
                ];
            }
            NoticeService::instance()->batchCreateNotice($noticeInsertData);
            // 生成待兑付记录
            foreach ($reqEnterpriseIds as $enterpriseId) {
                $freePolicyInsertData[] = [
                    'enterprise_id' => $enterpriseId,
                    'policy_id'     => $req['id'],
                ];
            }
            DataEnterpriseFreePolicy::insertAll($freePolicyInsertData);
            $this->success('保存成功！', 'javascript:history.back()');
        }
    }

    /**
     * 修改文章状态
     */
    public function state()
    {
        DataNewsItem::mSave($this->_vali([
            'status.in:0,1'  => '状态值范围异常！',
            'status.require' => '状态值不能为空！',
        ]));
    }

    /**
     * 删除文章内容
     */
    public function remove()
    {
        DataNewsItem::mDelete();
    }

    /**
     * 文章内容选择
     * @login true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function select()
    {
        $this->get['status'] = 1;
        $this->index();
    }

    public function getQybqList()
    {
        $biaoqian = Db::name('data_qiye_biaoqian')->where('deleted', 0)->select()->toArray();
        return_msg(200, 'success', $biaoqian);
    }

    public function shenhe()
    {
        $id = input('id');
        Db::name("data_msjx")->where('id', $id)->update(['tj_status' => 2]);
        Db::name("data_msjx_user")->where('msjx_id', $id)->update(['tj_status' => 2]);
        $this->success('操作成功！', 'javascript:history.back()');
    }

    public function gongshi()
    {
        $id = input('id');
        Db::name("data_msjx")->where('id', $id)->update(['tj_status' => 3]);
        Db::name("data_msjx_user")->where('msjx_id', $id)->update(['tj_status' => 3]);
        $this->success('操作成功！', 'javascript:history.back()');
    }


    public function luoshi()
    {
        $id = input('id');
        Db::name("data_msjx")->where('id', $id)->update(['tj_status' => 4]);
        Db::name("data_msjx_user")->where('msjx_id', $id)->update(['tj_status' => 4]);
        $this->success('操作成功！', 'javascript:history.back()');
    }
}